<script setup lang="ts">

defineOptions({name: 'CustomModule'})
import { ElMessageBox } from 'element-plus'
import {useTable} from '@/composables/useTable'
import {formatEnumData, dateFormat} from '@/utils/helper'
import {useI18n} from 'vue-i18n'
import {getCustomModuleList, deleteCustomModule} from '@/api/custom-module'
import {getEnumData} from '@/api/enum'
import {getLanguageData} from '@/api/language'
import Search from './modules/search.vue'
import Create from './modules/create.vue'
import Update from './modules/update.vue'
import Field from './modules/field.vue'

/**
 * 变量部分
 */
const {t} = useI18n()
const enumData = ref<any>({})
const enumDataFormat = ref<any>({})
const languageData = ref<any>({})
const sortField = new Map<string, any>()
const createRef = ref()
const updateRef = ref()
const fieldRef = ref()

onMounted(async () => {
	await getLanguage()
	await getEnum()
})

/**
 * 表格函数
 */
const {
	columns,
	columnChecks,
	data,
	loading,
	pagination,
	updateColumn,
	searchParams,
	handleSizeChange,
	handleCurrentChange,
	resetSearchParams,
	refreshData,
	getDataDebounced,
} = useTable({
	// 核心配置
	core: {
		apiFn: getCustomModuleList,
		apiParams: {
			page: 1,
			limit: 10,
		},
		columnsFactory: () => [
			{prop: 'operate', label: t('common.operate'), width: 150, useSlot: true},
			{prop: 'name', minWidth: 120},
			{prop: 'limit', minWidth: 80},
			{prop: 'sort', label: t('common.field.sort'), minWidth: 90, sortable: 'custom'},
			{
				prop: 'createTime', label: t('common.field.createTime'), width: 170, useSlot: true,
				sortable: 'custom',
			},
			{
				prop: 'updateTime', label: t('common.field.updateTime'), width: 170, useSlot: true,
				sortable: 'custom',
			},
		]
	}
})

/**
 * 获取枚举数据
 */
const getEnum = async () => {
	enumData.value = await getEnumData({modules: ['customModule']})
	enumDataFormat.value = formatEnumData(enumData.value)
}

/**
 * 获取语言数据
 */
const getLanguage = async () => {
	const res: any = await getLanguageData({modules: ['customModule']});
	languageData.value = {...res};
	for (let key in res.customModule.field) updateColumn?.(key, {label: res.customModule.field[key]})
}

/**
 * 处理排序改变
 * @param params
 */
const handleSortChange = (params: any) => {
	const hasProp = sortField.has(params.prop);
	if (hasProp && params.order === null) sortField.delete(params.prop)
	else sortField.set(params.prop, params.order)
	let orderBy: any = {};
	for (const [key, value] of sortField) if (value) orderBy[key] = value === 'ascending' ? 'asc' : 'desc'
	// 搜索参数赋值
	Object.assign(searchParams, {orders: {...orderBy}})
	getDataDebounced()
}

/**
 * 处理表头单元格的 className 的回调方法
 * @param column
 */
const handleHeaderCellClassName = ({column}: { column: any }) => {
	if (sortField.has(column.property)) column.order = sortField.get(column.property)
	return ''
}

/**
 * 处理搜索重置
 * @param filterData
 */
const handleSearchReset = (filterData: any) => {
	resetSearchParams()
	Object.assign(searchParams, {...filterData})
	getDataDebounced()
}

/**
 * 处理搜索确认
 * @param filterData
 */
const handleSearchConfirm = (filterData: any) => {
	resetSearchParams()
	Object.assign(searchParams, {...filterData})
	getDataDebounced()
}

/**
 * 处理显示创建
 */
const handleShowCreate = () => createRef.value.open()

/**
 * 处理显示更新
 */
const handleShowUpdate = (id: number | string) => updateRef.value.open(id)

/**
 * 处理显示字段配置
 */
const handleShowField = (id: number | string) => fieldRef.value.open(id)

/**
 * 处理删除
 * @param id
 */
const handleDelete = async (id: number | string) => {
	ElMessageBox.confirm(t('common.deleteTip'), t('common.deleteConfirm'), {
		confirmButtonText: t('common.confirm'), cancelButtonText: t('common.cancel'),
		type: 'error', draggable: true
	}).then(() => {
		loading.value = true
		deleteCustomModule({customModuleId: id}).then(() => refreshData()).finally(() => loading.value = false)
	}).catch(() => {
	})
}
</script>

<!-- art-full-height 自动计算出页面剩余高度 -->
<!-- art-table-card 一个符合系统样式的 class，同时自动撑满剩余高度 -->
<!-- 更多 useTable 使用示例请移步至 功能示例 下面的 高级表格示例 -->
<template>
	<div class="art-full-height">
		<!-- 搜索栏 -->
		<Search :enumData="enumData" :languageData="languageData" @reset="handleSearchReset"
			@search="handleSearchConfirm"/>

		<ElCard class="art-table-card" shadow="never">
			<!-- 表格头部 -->
			<ArtTableHeader v-model:columns="columnChecks" :loading="loading" @refresh="refreshData">
				<template #left>
					<ElSpace wrap>
						<ElButton v-auth="'customModuleCreate'" @click="handleShowCreate"
							  v-ripple>
							{{ t('common.create') }}
						</ElButton>
					</ElSpace>
				</template>
			</ArtTableHeader>

			<!-- 表格 -->
			<ArtTable
				:loading="loading"
				:data="data"
				:columns="columns"
				:show-overflow-tooltip="true"
				:header-cell-class-name="handleHeaderCellClassName"
				:pagination="pagination"
				@pagination:size-change="handleSizeChange"
				@pagination:current-change="handleCurrentChange"
				@sort-change="handleSortChange"
			>
				<template #operate="{row}">
					<ArtButtonTable type="edit" v-auth="'customModuleUpdate'"
							@click="handleShowUpdate(row.customModuleId)"/>
					<ArtButtonTable type="delete" v-auth="'customModuleDelete'"
							@click="handleDelete(row.customModuleId)"/>
					<ArtButtonTable type="setting" v-auth="'customModuleField'"
							@click="handleShowField(row.customModuleId)"/>
				</template>
				<template #createTime="{row}">{{ dateFormat(row.createTime) }}</template>
				<template #updateTime="{row}">{{ dateFormat(row.updateTime) }}</template>
			</ArtTable>
		</ElCard>
		<Create ref="createRef" :enumData="enumData" :languageData="languageData" @success="refreshData"/>
		<Update ref="updateRef" :enumData="enumData" :languageData="languageData" @success="refreshData"/>
		<Field ref="fieldRef"/>
	</div>
</template>

<style lang="scss" scoped>

</style>
